<template>
  <div>
    <el-dialog
      :visible.sync="show"
      width="600px"
      v-loading="loading"
      v-if="show"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="页面导出" name="first">
          <el-form ref="pageExport" label-position="top">
            <el-form-item label="请选择您需要导出的页面">
              <el-checkbox-group v-model="checkboxValue" size="small">
                <el-checkbox
                  v-for="item in pageList"
                  :label="item.page_key"
                  :key="item.id"
                  >{{ item.text }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="页面导入" name="second">
            <el-steps
              class="stepStyle"
              simple
              :space="200"
              :align-center="true"
              :active="stepActive"
              finish-status="success"
            >
              <el-step title="上传文件"></el-step>
              <el-step title="选择页面"></el-step>
              <el-step title="完成"></el-step>
            </el-steps>
            <div
              style="
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: space-between;
                padding: 50px 0;
              "
            >
              <i
                v-if="stepActive == 1"
                class="el-icon-upload"
                style="font-size: 150px"
              ></i>
              <el-icon
                v-if="stepActive == 3"
                class="el-icon-circle-check"
                style="font-size: 150px; color: #333333"
              >
              </el-icon>
              <div v-if="stepActive == 1" style="text-align: center; margin: 40px auto">
                <el-alert
                  title="请选择.udpage后缀结尾的文件进行导入，导入成功后原先的页面将会被覆盖"
                  type="warning"
                  :closable="false"
                  show-icon
                >
                </el-alert>
              </div>
              <el-form v-if="stepActive == 2" ref="pageExport" label-position="top">
                <el-form-item label="请选择您需要导入的页面">
                  <el-checkbox-group v-model="importData.keys" size="small">
                    <el-checkbox
                      v-for="item in pageList"
                      :label="item.page_key"
                      :key="item.id"
                      :disabled="item.disabled"
                      >{{ item.text }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-form>
              <el-upload
                v-loading="uploading"
                action="/api/admin6/pages/get_keys"
                :show-file-list="false"
                :headers="headers"
                element-loading-text="处理中"
                list-type="text"
                :multiple="true"
                :before-upload="beforeUpload"
                :data="importData"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :style="{ display: 'inline-block' }"
              >
                <el-button v-if="stepActive == 1" slot="trigger" type="primary"
                  >选择文件</el-button
                >
              </el-upload>
              <el-button
                v-if="stepActive == 2"
                type="primary"
                @click="submitUpload"
                :disabled="startImportBtnStatus"
                >开始导入
              </el-button>
              <el-button v-if="stepActive == 3" type="primary" @click="importComplete"
                >确定</el-button
              >
            </div>
        </el-tab-pane>
      </el-tabs>
      <div v-if="activeName === 'first'" slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-close" @click="show = false"
          >取消</el-button
        >
        <el-button
          size="small"
          icon="el-icon-check"
          type="primary"
          @click="startExport"
          :disabled="startExportBtnStatus"
          >开始导出</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportPage, getPageFileKes, importPage } from "@/api/page";

export default {
  name: "pagesImportExport",
  props: {},
  components: {},
  data() {
    return {
      show: false,
      loading: false,
      uploading: false,
      activeName: "first",
      checkboxValue: [],
      importData: {
        keys: [],
      },
      stepActive: 1,
      file: null,
    };
  },
  computed: {
    startExportBtnStatus: function () {
      if (this.checkboxValue.length == 0) {
        return true;
      }
      return false;
    },
    startImportBtnStatus: function () {
      if (this.importData.keys.length == 0) {
        return true;
      }
      return false;
    },
    pageList: {
      get() {
        return this.$store.state.pagemaker.pageTabbars;
      },
    },
    headers: function () {
      return {
        Authorization: `Bearer ${this.$store.state.user.token}`,
      };
    },
    uploadAllowedExtension: function () {
      return this.$store.state.myconfig.upload_allowed_extension;
    },
  },
  created() {},
  methods: {
    importComplete() {
      this.show = false;
      this.importData.keys = [];
      this.stepActive = 1;
      this.file = null;
      this.pageList.forEach(item=>{
        item.disabled = false;
      })
    },
    submitUpload() {
      let formData = new FormData();
      formData.append("file", this.file);
      formData.append("keys", this.importData.keys);
      importPage(formData).then((resp) => {
        this.loading = false;
        this.uploading = false;

        if (resp.code != 0) {
          // this.$message.error(resp.msg);
          return;
        }

        this.stepActive = 3;
        this.$message.success(resp.message);
        var pagemaker = this.$store.state.pagemaker;
        this.$store.dispatch("pagemaker/loadPage", pagemaker.pageId);
      });
    },
    startExport() {
      if (this.checkboxValue.length == 0) {
        this.$message.error("请选择需要导出的页面");
        return;
      }

      this.loading = true;
      exportPage(this.checkboxValue)
        .then((resp) => {
          const blob = new Blob([resp], {
            type: "application/json",
          });
          const link = document.createElement("a");
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", "pages.udpage"); // 设置下载文件的名称
          document.body.appendChild(link);
          link.click();
          // 释放URL对象
          URL.revokeObjectURL(link.href);
          this.$message.success("导出成功");
        })
        .finally(() => {
          this.loading = false;
          this.show = false;
          this.checkboxValue = [];
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },
    handleClick(tab) {
      this.activeName = tab.name;
      this.checkboxValue = [];
      this.importData.keys = [];
    },
    showdialog() {
      this.show = true;
    },
    uploadError(res) {
      this.uploading = false;

      var obj = JSON.parse(res.message);
      this.$message.error(obj.message);
    },

    uploadSuccess(res) {
      if (this.stepActive == 1) {
        this.loading = false;
        this.uploading = false;
        if (res.code !== 0) {
          this.$message.error(res.message);
          this.importData.keys = [];
          return;
        }

        this.importData.keys = res.data;
        //将importData中的keys和pageList的对象中的page_key进行对比，不相同的禁用
        this.pageList.forEach((item) => {
          if (!this.importData.keys.includes(item.page_key)) {
            item.disabled = true;
          }
        });


        this.stepActive = 2;
      } else {
        this.loading = false;
        this.uploading = false;
        // this.show = false;
        console.log("res is", res);
        if (res.code !== 0) {
          this.$message.error(res.message);
          return;
        }
        this.stepActive = 3;
        this.$message.success(res.message);
        var pagemaker = this.$store.state.pagemaker;
        this.$store.dispatch("pagemaker/loadPage", pagemaker.pageId);
      }
    },
    beforeUpload(file) {
      this.loading = true;
      let errorMsg = "";
      const extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      if ("udpage" != extension) {
        errorMsg = "上传文件的格式不正确";
      }
      if (errorMsg) {
        this.$message({
          message: errorMsg,
          type: "warning",
        });
        this.loading = false;
        return false;
      }

      this.file = file;

      return true;
    },
  },
};
</script>

<style scoped>
.stepStyle::v-deep .el-step__head.is-finish {
  color: #333333 !important;
  border-color: #333333 !important;
}

.stepStyle::v-deep .el-step__head.is-success {
  color: #333333 !important;
  border-color: #333333 !important;
}
</style>
